package cn.z2huo.demo.spring.transactional.service;

import cn.z2huo.demo.model.dataobject.user.UserDO;
import cn.z2huo.demo.spring.transactional.dao.UserDAO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *
 * @author z2huo
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserDAO userDAO;

    private final UserService2 userService2;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
    public void processInvalidUserData() {
        for (int pageSize = 2, pageNo = 1; ; pageNo++) {
            List<UserDO> userDOList = userDAO.listInvalidUser(pageNo, pageSize);
            if (CollectionUtils.isEmpty(userDOList)) {
                break;
            }
            userDOList.parallelStream().forEach(userDO -> {
                try {
                    userService2.updateUserValidFlag(userDO.getUserCode(), userDO.getId());
                } catch (Exception e) {
                    log.error("process data error, userCode is {}, userId is {}",
                            userDO.getUserCode(), userDO.getId());
                }
            });
        }
    }

}
